import { defineComponent, ref, provide, toRaw, inject, onMounted, computed } from 'vue'
import dyFormApi from '@/service/api/dyForm'
import { useMessage, NButton } from 'naive-ui'
import { useRoute, useRouter } from 'vue-router'
import addEdit from '@/basic/addEdit/index'
import { getFromTypeKeys, getQuestionsInfo } from '@/utils/dyForm'
import TheSide from './moving/TheSide'
import PreView from './moving/PreView'
import TheEdit from './moving/TheEdit'
import CodeEdit from '@/components/nComponents/CodeEdit'
import EditForm from '@/components/yFormData/trends/Edit'
import CodeDirectory from '@/components/yFormData/directory/index'
import pageStyle from './styles/index.module.scss'
import type { questionSideListState, basicState, addEditState } from '@/types/baseConfig'
import dictionaryApi from '@/service/api/dictionary'
export default defineComponent({
  setup() {
    const route: any = useRoute()
    const router: any = useRouter()
    const toast = useMessage()
    const $clone = inject('$clone') as <T>(data: T) => T
    const addEditInfo: any = ref({
      addEdit
    })

    const handWkf = () => {
      console.log('开发中...')
    }

    const editChange = (e: questionSideListState) => {
      if (curren.value.length > 0) {
        const arr = $clone(curren.value)
        const getChilder = (list: questionSideListState[], i = 0) => {
          return list.map((el: questionSideListState, index: number) => {
            if (index === arr[i]) {
              if (i === arr.length - 1) {
                return e
              }
              if (el?.RowLayoutForm && el?.RowLayoutForm?.childer) {
                el.RowLayoutForm.childer = getChilder(el.RowLayoutForm.childer, i + 1)
              }
            }
            return el
          })
        }
        if (curren.value.length > 1) {
          questions.value = getChilder(questions.value)
        } else {
          questions.value[curren.value[0]] = e
        }
      }
    }

    const baseChange = (e: basicState) => {
      addEditInfo.value.addEdit.basic = e
    }
    const addEditChange = (e: addEditState) => {
      addEditInfo.value.addEdit = e
    }
    const save = async () => {
      addEditInfo.value.addEdit.questions = toRaw(questions.value)
      const params = $clone(addEditInfo.value)
      params.addEdit = JSON.stringify(params.addEdit)
      const { code, message } = await dyFormApi.edit(params)
      if (code !== 200) {
        toast.error(message)
        return
      }
      toast.success('保存成功')
    }

    /**
     *  题目
     * */
    const curren = ref<number[]>([])
    const currenUid = ref<string>('')
    provide('curren', curren)
    const compData = computed(() => {
      let newInfo: any = {}
      if (curren.value.length > 0) {
        newInfo = questions.value[curren.value[0]]
        if (curren.value.length > 1) {
          curren.value.forEach((el: number, index: number) => {
            if (index !== 0) {
              newInfo = newInfo.RowLayoutForm.childer[el]
            }
          })
        }
      }
      return newInfo || {}
    })
    const setCurren = (e: number[]) => {
      curren.value = e
    }
    const editRef = ref()
    const setCurenUid = (e: string) => {
      currenUid.value = e
      editRef.value.tabCurrenChange(0)
    }
    provide('dySlots', {})
    provide('currenUid', currenUid)
    provide('setCurenUid', setCurenUid)
    provide('setCurren', setCurren)
    const questions = ref<questionSideListState[]>([])
    provide('queryForm', undefined)
    provide('questions', questions)
    const handAdd = (e: any) => {
      questions.value.push(getQuestionsInfo(e))
      curren.value = [questions.value.length - 1]
    }

    const pageOptionsInfo = ref<any>({})
    const handOptionsInfoChange = async () => {
      const typeKeys = getFromTypeKeys(questions.value)
      const oldTypeKeys = Object.keys(pageOptionsInfo.value)
      oldTypeKeys.forEach((el: string) => {
        if (!typeKeys.includes(el)) {
          delete pageOptionsInfo.value[el]
        }
      })
      const newtypeKey = typeKeys.filter((el: string) => {
        return !oldTypeKeys.includes(el)
      })
      const { data } = await dictionaryApi.keyLists({
        typeKeys: newtypeKey
      })
      data.forEach((el: any) => {
        pageOptionsInfo.value[el.typeKey] = el.childer
      })
    }
    provide('pageOptionsInfo', pageOptionsInfo)
    provide('handOptionsInfoChange', handOptionsInfoChange)

    /**
     *  初始化题目
     * */
    const init = async () => {
      const { data } = await dyFormApi.detail(route.query.id)
      data.addEdit = JSON.parse(data.addEdit)
      addEditInfo.value = data
      questions.value = data.addEdit.questions
      if (questions.value.length > 0) {
        curren.value = [0]
        setCurenUid(questions.value[0].uid)
      }
      handOptionsInfoChange()
      // directoryRef.value.open(data.addEdit)
    }
    const handRemove = () => {
      curren.value = []
      currenUid.value = ''
      questions.value = []
    }
    const codeRef = ref()
    const importJson = () => {
      addEditInfo.value.addEdit.questions = toRaw(questions.value)
      const params = $clone(addEditInfo.value)
      codeRef.value.open({
        key: '',
        labelKey: '',
        title: '导入JSON',
        isDesc: false,
        value: params.addEdit,
        language: 'json'
      })
    }
    const exportJson = () => {
      addEditInfo.value.addEdit.questions = toRaw(questions.value)
      const params = $clone(addEditInfo.value)
      const json = JSON.stringify(params.addEdit)
      const link = document.createElement('a')
      link.href = 'data:text/json;charset=utf-8,' + encodeURIComponent(json)
      link.download = `${addEditInfo.value.name}.json`
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
    const exportCode = () => {
      toast.warning('开发中...')
    }
    const handSfc = () => {
      toast.warning('开发中...')
    }
    const codeChange = (e: any) => {
      addEditInfo.value.addEdit = e
      questions.value = e.questions
    }
    const handPrive = () => {
      addEditInfo.value.addEdit.questions = toRaw(questions.value)
      const params = $clone(addEditInfo.value)
      if (params.addEdit.questions.length === 0) {
        toast.error('题型为空')
        return
      }
      addRef.value.open(addEditInfo.value.id)
    }

    const handBack = () => {
      router.go(-1)
    }

    const addRef = ref()
    const directoryRef = ref()
    onMounted(() => {
      init()
    })
    return () => (
      <>
        <div class={pageStyle.xyLayouts}>
          <div class="appManagementHeaderWrap">
            <div class="sc-gwVKww">
              <div class="back" onClick={handBack}>
                <i class="el-icon-back"></i>
                <span class="font-bold">正在编辑表单&nbsp;:</span>
                <span class="formName">{addEditInfo.value.name}</span>
              </div>
            </div>
            <div class="main"></div>
            <div class="nav-right">
              <div class="btns">
                <NButton size="small" onClick={handBack}>
                  关闭
                </NButton>
                <NButton style={{ marginLeft: '10px' }} size="small" type="primary" onClick={save}>
                  保存
                </NButton>
              </div>
            </div>
          </div>
          <div class="moving">
            <TheSide onAdd={handAdd} />
            <PreView
              comp-data={addEditInfo.value.addEdit.basic}
              onRemove={handRemove}
              onPrive={handPrive}
              onImportJson={importJson}
              onExportJson={exportJson}
              onExportCode={exportCode}
              onSfc={handSfc}
            />
            <TheEdit
              ref={editRef}
              comp-data={compData.value}
              add-edit={addEditInfo.value.addEdit}
              onSave={editChange}
              onBasicChange={baseChange}
              onAddEditChange={addEditChange}
            />
          </div>
        </div>
        <CodeEdit ref={codeRef} onSave={codeChange} />
        <EditForm ref={addRef} />
        <CodeDirectory ref={directoryRef} />
      </>
    )
  }
})
